<template>
  <div
    class="head-image"
    @click="showUserInfo"
    :style="{ cursor: isShowUserInfo ? 'pointer' : null }"
  >
    <img
      class="avatar-image"
      v-show="url"
      :src="url"
      :style="avatarImageStyle"
      loading="lazy"
    />
    <div class="avatar-text" v-show="!url" :style="avatarTextStyle">
      {{ name?.substring(0, 2).toUpperCase() }}
    </div>
    <!-- <div v-show="online" class="online" title="用户当前在线"></div> -->
    <slot></slot>
  </div>
</template>

<script setup>
import { ref, computed, toRefs, defineProps } from "vue";
import { useUserStore } from "@/store/userStore";
import axios from "axios";

const colors = [
  "#5daa31",
  "#c7515a",
  "#e03697",
  "#85029b",
  "#c9b455",
  "#326eb6",
];

// Props
const props = defineProps({
  id: {
    type: Number,
  },
  size: {
    type: Number,
    default: 42,
  },
  width: {
    type: Number,
  },
  height: {
    type: Number,
  },
  radius: {
    type: String,
    default: "50%",
  },
  url: {
    type: String,
  },
  name: {
    type: String,
    default: null,
  },
  online: {
    type: Boolean,
    default: false,
  },
  isShowUserInfo: {
    type: Boolean,
    default: true,
  },
});
const { width, height, size, id, radius, url, name, online, isShowUserInfo } =
  toRefs(props);

// Store
const store = useUserStore();

// Computed properties
const avatarImageStyle = computed(() => {
  const w = width.value || size;
  const h = height.value || size;
  return `width:${w}px; height:${h}px; border-radius: ${radius.value};`;
});

const avatarTextStyle = computed(() => {
  const w = width.value || size;
  const h = height.value || size;
  return `
    width: ${w}px; height:${h}px;
    background-color: ${name.value ? textColor.value : "#fff"};
    font-size:${w * 0.35}px;
    border-radius: ${radius.value};
  `;
});

const textColor = computed(() => {
  let hash = 0;
  if (name.value) {
    for (let i = 0; i < name.value.length; i++) {
      hash += name.value.charCodeAt(i);
    }
  }
  return colors[hash % colors.length];
});

// Methods
const showUserInfo = (e) => {
  if (!isShowUserInfo.value) return;
  if (id.value && id.value > 0) {
    axios
      .get(`/user/find/${id.value}`)
      .then((response) => {
        store.commit("setUserInfoBoxPos", e);
        store.commit("showUserInfoBox", response.data);
      })
      .catch((error) => {
        console.error("Error fetching user info:", error);
      });
  }
};
</script>

<style scoped lang="scss">
.head-image {
  position: relative;

  .avatar-image {
    position: relative;
    overflow: hidden;
    display: block;
  }

  .avatar-text {
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 28px;
  }

  .online {
    position: absolute;
    right: -5px;
    bottom: 0;
    width: 12px;
    height: 12px;
    background: limegreen;
    border-radius: 50%;
    border: 2px solid white;
  }
}
</style>
